<template>
  <div class="product-category">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>商品分类管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增分类
          </el-button>
        </div>
      </template>

      <!-- 分类树形表格 -->
      <el-table
        :data="categoryList"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column prop="name" label="分类名称" width="200" />
        <el-table-column prop="code" label="分类编码" width="150" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="sort" label="排序" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="success" size="small" @click="handleAddChild(row)">
              添加子分类
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分类表单对话框 -->
    <CategoryForm
      :visible="formVisible"
      :category-data="currentCategory"
      :is-edit="isEdit"
      :parent-category="parentCategory"
      @update:visible="formVisible = $event"
      @success="handleFormSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

// 分类数据接口
interface Category {
  id: number
  name: string
  code: string
  description?: string
  parentId?: number
  sort: number
  status: number
  createTime: string
  children?: Category[]
}

// 分类列表
const categoryList = ref<Category[]>([
  {
    id: 1,
    name: '电子产品',
    code: 'ELECTRONICS',
    description: '各类电子设备',
    sort: 1,
    status: 1,
    createTime: '2024-01-01 00:00:00',
    children: [
      {
        id: 11,
        name: '手机',
        code: 'PHONE',
        description: '智能手机',
        parentId: 1,
        sort: 1,
        status: 1,
        createTime: '2024-01-01 00:00:00'
      },
      {
        id: 12,
        name: '电脑',
        code: 'COMPUTER',
        description: '台式机和笔记本',
        parentId: 1,
        sort: 2,
        status: 1,
        createTime: '2024-01-01 00:00:00'
      }
    ]
  },
  {
    id: 2,
    name: '服装',
    code: 'CLOTHING',
    description: '各类服装',
    sort: 2,
    status: 1,
    createTime: '2024-01-01 00:00:00',
    children: [
      {
        id: 21,
        name: '男装',
        code: 'MEN_CLOTHING',
        description: '男性服装',
        parentId: 2,
        sort: 1,
        status: 1,
        createTime: '2024-01-01 00:00:00'
      },
      {
        id: 22,
        name: '女装',
        code: 'WOMEN_CLOTHING',
        description: '女性服装',
        parentId: 2,
        sort: 2,
        status: 1,
        createTime: '2024-01-01 00:00:00'
      }
    ]
  }
])

// 表单对话框
const formVisible = ref(false)
const currentCategory = ref<Category | null>(null)
const parentCategory = ref<Category | null>(null)
const isEdit = ref(false)

// 新增分类
const handleAdd = () => {
  currentCategory.value = null
  parentCategory.value = null
  isEdit.value = false
  formVisible.value = true
}

// 添加子分类
const handleAddChild = (parent: Category) => {
  currentCategory.value = null
  parentCategory.value = parent
  isEdit.value = false
  formVisible.value = true
}

// 编辑分类
const handleEdit = (category: Category) => {
  currentCategory.value = { ...category }
  parentCategory.value = null
  isEdit.value = true
  formVisible.value = true
}

// 删除分类
const handleDelete = async (category: Category) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除分类 "${category.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟删除操作
    const removeCategory = (list: Category[], id: number): Category[] => {
      return list.filter(item => {
        if (item.id === id) {
          return false
        }
        if (item.children) {
          item.children = removeCategory(item.children, id)
        }
        return true
      })
    }
    
    categoryList.value = removeCategory(categoryList.value, category.id)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 表单成功回调
const handleFormSuccess = (category: Category) => {
  formVisible.value = false
  
  if (isEdit.value) {
    // 更新分类
    const updateCategory = (list: Category[], updatedCategory: Category): Category[] => {
      return list.map(item => {
        if (item.id === updatedCategory.id) {
          return { ...updatedCategory }
        }
        if (item.children) {
          item.children = updateCategory(item.children, updatedCategory)
        }
        return item
      })
    }
    
    categoryList.value = updateCategory(categoryList.value, category)
  } else {
    // 新增分类
    category.id = Date.now() // 模拟ID生成
    category.createTime = new Date().toLocaleString()
    
    if (parentCategory.value) {
      // 添加子分类
      const addChildCategory = (list: Category[], parentId: number, newCategory: Category): Category[] => {
        return list.map(item => {
          if (item.id === parentId) {
            if (!item.children) {
              item.children = []
            }
            item.children.push({ ...newCategory })
          } else if (item.children) {
            item.children = addChildCategory(item.children, parentId, newCategory)
          }
          return item
        })
      }
      
      categoryList.value = addChildCategory(categoryList.value, parentCategory.value.id, category)
    } else {
      // 添加顶级分类
      categoryList.value.push({ ...category })
    }
  }
}

// 初始化
onMounted(() => {
  // 这里可以调用API获取分类列表
})
</script>

<style scoped lang="scss">
.product-category {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
</style>

